package com.screenrouter.service;

import com.screenrouter.model.ScreenConfig;
import com.screenrouter.model.WebSocketMessage;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

@Service
public class ScreenService {
    
    private final SimpMessagingTemplate messagingTemplate;
    private ScreenConfig currentConfig;
    
    public ScreenService(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
        // 初始化默认配置
        this.currentConfig = new ScreenConfig(
            "auto", 
            10, 
            "首页", 
            new String[]{"首页", "数据概览", "实时监控", "统计分析", "系统设置"}
        );
    }
    
    public ScreenConfig getCurrentConfig() {
        return currentConfig;
    }
    
    public void updateConfig(ScreenConfig config) {
        this.currentConfig = config;
        broadcastConfig();
    }
    
    public void switchToPage(String pageName) {
        if (Arrays.asList(currentConfig.getPages()).contains(pageName)) {
            currentConfig.setCurrentPage(pageName);
            broadcastPageSwitch(pageName);
        }
    }
    
    public void setMode(String mode) {
        currentConfig.setMode(mode);
        broadcastConfig();
    }
    
    public void setInterval(Integer interval) {
        currentConfig.setInterval(interval);
        broadcastConfig();
    }
    
    private void broadcastConfig() {
        WebSocketMessage message = new WebSocketMessage(
            "config",
            currentConfig,
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        );
        messagingTemplate.convertAndSend("/topic/screen-config", message);
    }
    
    private void broadcastPageSwitch(String pageName) {
        WebSocketMessage message = new WebSocketMessage(
            "switch",
            pageName,
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        );
        messagingTemplate.convertAndSend("/topic/screen-switch", message);
    }
    
    public void broadcastStatus() {
        WebSocketMessage message = new WebSocketMessage(
            "status",
            currentConfig,
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        );
        messagingTemplate.convertAndSend("/topic/screen-status", message);
    }
} 